import noToken from './noToken.js';
import tools from '@/utils/tools.js';
import store from '@/store';



const noShowTips = ['/api/mediaRoom/joinMediaRoomApp', '/api/mediaRoom/giveGiftsApp']
/**
 * @description 请求函数
 * @param {Object} options 请求配置
 * @param {Boolean} loading 是否显示loading弹窗
 * @param {String} text loading 提示文字
 * @param {String} url 请求接口地址
 * @param {Object} data 请求接口的参数
 * @param {String} method 请求方式
 * @param {Object} header 请求方式
 * @return null
 */
export default function(options) {
	return new Promise(async (resolve, reject) => {
		let config = {
			"loading": true, //是否需要loading弹窗
			"text": 'loading..', //loading中提示
			"url": '', //请求接口地址
			"data": {},
			"method": 'GET',
			"header": {
				"ApiAuthorization": '',
				"Content-Type": ''
			},
		}
		console.log('请求配置', options);
		const params = await beforeIntercept(tools.deepMerge(config, options))

		params.url = import.meta.env.VITE_API_URL + params.url;
		switch (params.method) {
			case 'body':
				params.method = 'POST'
				params.header["Content-Type"] = 'multipart/form-data';
				break;
			case 'DELETE':
				params.header["Content-Type"] = 'application/x-www-form-urlencoded';
				break;
			default:
				if (params.header["Content-Type"] === '' && params.method === 'POST') {
					params.header["Content-Type"] = 'application/x-www-form-urlencoded'

				} else {
					params.header["Content-Type"] = 'application/json'
				}
				break;
		}

		console.log('请求数据', params);
		uni.request({
			url: params.url,
			method: params.method,
			data: params.data,
			header: params.header,
			timeout: 30000,
			success(result) {
				try {
					// tools.closeLoading();
					afterIntercept(result).then((res) => {
						resolve(res)
					}).catch((err) => {
						console.error(err);
						reject(err)
					})
				} catch (e) {
					// tools.closeLoading();
					//TODO handle the exception
					console.error(e, '回调异常')
				}
			},
			fail(err) {
				console.log('请求异常')
				reject(err)
			},
		})

	})
}
//请求接口前的拦截
function beforeIntercept(event) {
	tools.showLoading()
	return new Promise((resolve, reject) => {
		// console.log(event);
		if (noToken.includes(event.url)) {
			event.header.ApiAuthorization = '';
			resolve(event);
		} else if (!noToken.includes(event.url)) {
			event['header'].ApiAuthorization = uni.getStorageSync('token') ||
				""; //token赋值
			resolve(event)
		}

	})
}

//请求接口结束
function afterIntercept(result) {
	tools.closeLoading();
	return new Promise((resolve, reject) => {
		if (result.statusCode === 200) {
			switch (result.data.code) {
				case 200:
					resolve(result.data);
					break;
				case 401:
					tools.showTips('Login Out', () => {
						// tools.jumpTo('/pages/client/account/loginSwiper')
						uni.$to('/pages/login/login')
					});

					// store.userStore.commit('userStore/$clearUserStore')
					reject(result.data);
					break;
				default:
					if (noShowTips.includes(result.data.path)) {

					} else {
						tools.showTips(result.data.msg || result.data.desc);
					}
					reject(result.data);
					break;
			}
		} else {
			tools.showTips(result.errMsg);
			reject(result.errMsg)
		}
	})
}